import functools

from flask import (
    Blueprint, g, redirect, render_template, request, session, url_for
)

from forumAPP.database import get_database_connection

bp = Blueprint('auth', __name__, url_prefix='/auth')


@bp.route('/register', methods=('GET', 'POST'))
def register():
    if request.method == 'GET':
        return render_template('/auth/register.html')

    # POST
    print("注册，用户输入:", request.form)
    nickname: str = request.form.get("nickname")
    password: str = request.form.get("password")
    career: str = request.form.get('career')
    gender: str = request.form.get('gender')
    region: str = request.form.get('region')
    print('内存接收:', nickname, password, career, gender, region,)


#  注册，用户输入: ImmutableMultiDict([('nickname', 'ahshhsd'), ('password', '1232134'),
# ('career', '哦呀'), ('gender', '女'), ('region', '西班牙')])
    conn = get_database_connection()
    SQL_code = '''
    INSERT INTO user (nickname, password, region, career, gender)
    VALUES (?,?,?,?,?);
    '''
    conn.execute(SQL_code, (nickname, password, region, career, gender,))
    conn.commit()

    return redirect(url_for("auth.login"))


@ bp.route('/login', methods=('GET', 'POST',))
def login():
    if request.method == 'GET':
        return render_template('/auth/login.html')
    # POST, 用户提交表单
    # ImmutableMultiDict([('nickname', '何为'), ('password', '1233425')])
    nickname: str = request.form.get('nickname')
    password: str = request.form.get('password')
    SQL_code: str = '''
    SELECT *
    FROM user AS u
    WHERE u.nickname=?;
    '''
    conn = get_database_connection()
    user = conn.execute(SQL_code, (nickname,)).fetchone()
    if user is None:
        g.error = '用户\"'+nickname+'\"不存在'
    elif user['password'] != password:
        g.error = '密码错误'
    else:
        g.error = None

    if user is not None:
        print('数据库查询结果:', user['numberID'], user['nickname'], user['password'])

    if g.error is not None:
        g.trial_nickname = nickname
        return render_template('/auth/login.html')

    session.clear()
    session['userID'] = user['numberID']

    # TODO
    return redirect(url_for('index'))


# 检查用户是否已登录
@ bp.before_app_request
def load_logged_in_user():
    print('检查登录状态...', end='')
    userID = session.get('userID')

    if userID is None:
        g.user = None
    else:
        g.user = get_database_connection().execute(
            'SELECT * FROM user WHERE numberID = ?', (userID,)
        ).fetchone()
    if g.user is not None:
        print('已登录用户:', g.user['numberID'],
              g.user['nickname'], g.user['password'])
    else:
        print(None)


@ bp.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('index'))


def login_required(view):
    @ functools.wraps(view)
    def wrapped_view(**kwargs):
        if g.user is None:
            return redirect(url_for('auth.login'))

        return view(**kwargs)

    return wrapped_view
